/*
Copyright  2018 Blockchain Technology and Application Joint Lab, Fintech Research Center of ISCAS.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
import React, {Component, PropTypes} from 'react';
import {browserHistory} from 'react-router';
import {Meteor} from 'meteor/meteor';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Subheader from 'material-ui/Subheader';
import Paper from 'material-ui/Paper';
import SvgIconBack from 'material-ui/svg-icons/navigation/chevron-left';
import Divider from 'material-ui/Divider';

import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {green400, blue300, red500, grey900} from 'material-ui/styles/colors';
import db from "../DBStore/db";
import repchain from '../api/repchainUtil'
import {
    VerifyPrvKeyWithPass,
} from '../api/cryptoHelper'
import {Buffer} from "buffer";

export default class AccountLogin extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // For login
            user_account: '',
            user_account_err: '',
            user_pass: '',
            user_pass_err: '',
            login_err: '',
        };
    }

    getChildContext() {
        return {muiTheme: getMuiTheme(baseTheme)};
    }

    handleLogin() {
        const {user_account, user_pass,} = this.state;
        //从数据库获取用户
        db.table('users').where({phone: user_account}).first().then((user) => {
            if (!user) {
                this.setState({login_err: '登录失败:用户不存在！'});
            } else {
                //验证密码
                if (!VerifyPrvKeyWithPass(user.prv_key_pem_encrypted, user_pass))
                    this.setState({login_err: '登录失败:用户名或者密码错误！'});
                else {
                    //短地址是否存在
                    if (user.account_address == 'none' || user.account_address == undefined) {
                        repchain.getAccountAddress(new Buffer(user.user_certificate_pem).toString('base64'), (err, res) => {
                            if (err) {
                                if(err.message.indexOf('不存在')>-1)
                                    this.setState({login_err: '证书未向repChian注册，请联系管理员！'});
                                else
                                    this.setState({login_err: err.message});
                            } else {
                                db.table('users').where({account_address: res}).first().then((addr_user)=>{
                                    if(!addr_user){
                                        db.table('users').update(user.id, {account_address: res}).then((id) => {
                                        console.log('add account_address success!')
                                        user.account_address = res;
                                        Meteor.call('account.setCurrentUser', user.account_address, (err, result) => {
                                            if (err) {
                                                console.log('Error: login set cur user failed, reason: ', err.error);
                                            }
                                        });
                                        Session.set('curUser', user);
                                        Session.set('isAdmin', user.isAdmin == undefined ? false : user.isAdmin);
                                        browserHistory.push('/tab0');
                                    })
                                    }else {
                                        db.table('users').delete(user.id).then(()=>{
                                            this.setState({login_err: "该证书已被使用，请换证书重新注册!"});
                                        })
                                    }
                                })

                            }
                        })
                    }else {
                        Meteor.call('account.setCurrentUser', user.account_address, (err, result) => {
                            if (err) {
                                console.log('Error: login set cur user failed, reason: ', err.error);
                            }
                        });
                        Session.set('curUser', user);
                        Session.set('isAdmin', user.isAdmin == undefined ? false : user.isAdmin);
                        browserHistory.push('/tab0');
                    }
                }
            }
        })
    }

    renderLogin() {
        const {user_account, user_account_err, user_pass, user_pass_err, login_err} = this.state;
        return (
            <Paper zDepth={5} style={{width: '90%', height: 'auto', top: '30%', left: '5%', position: 'absolute'}}>
                <h1 style={{fontWeight: 'normal', fontFamily: 'sans-serif',}}>
                    <FlatButton
                        label='返回'
                        icon={<SvgIconBack/>}
                        onClick={(e) => {
                            browserHistory.push('/tab0');
                        }}
                    />
                    <div id='login_title'>登录</div>
                </h1>
                <Divider style={{marginTop: '-1%', marginLeft: '5%', border: '0.02px dashed'}}/>
                <Subheader style={{color: red500, paddingLeft: '5%'}}>{login_err}</Subheader>
                <TextField
                    hintText='输入手机号'
                    floatingLabelStyle={{color: blue300}}
                    floatingLabelText='用户名'
                    defaultValue={user_account}
                    errorText={user_account_err}
                    style={{marginLeft: '5%', width: '90%'}}
                    onChange={(e, newValue) => {
                        const user_account = newValue;
                        if (user_account == '')
                            this.setState({user_account: user_account, user_account_err: '用户名不可为空'});
                        else
                            this.setState({user_account: user_account, user_account_err: ''});
                    }}
                /><br/>
                <TextField
                    type='password'
                    hintText='输入密码'
                    floatingLabelStyle={{color: blue300}}
                    floatingLabelText='密码'
                    errorText={user_pass_err}
                    style={{marginLeft: '5%', width: '90%'}}
                    onChange={(e, newValue) => {
                        const user_pass = newValue;
                        if (user_pass == '')
                            this.setState({user_pass: user_pass, user_pass_err: '密码不可为空'});
                        else
                            this.setState({user_pass: user_pass, user_pass_err: ''});
                    }}
                /><br/>
                <div id='login_buttons_holder'>
                    <div id='login_buttons'>
                        <RaisedButton
                            label='登录'
                            primary={user_account != '' && user_pass != ''}
                            disabled={user_account == '' || user_pass == ''}
                            style={{marginRight: 15}}
                            onClick={this.handleLogin.bind(this)}
                        />
                        <RaisedButton
                            label='注册'
                            primary={true}
                            onClick={e=>{browserHistory.push('/account_register')}}
                        />
                    </div>
                </div>
            </Paper>
        );
    }

    render() {
        return (
            <div style={{maxWidth: 450, maxHeight: 780, margin: 'auto'}}>
                {this.renderLogin()}
            </div>
        );
    }
}

AccountLogin.childContextTypes = {
    muiTheme: React.PropTypes.object.isRequired,
};